package cn.wolfcode.wolf2w.interceptor;


import cn.wolfcode.wolf2w.cache.redis.service.IUserInfoRedisService;
import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.util.JsonResult;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class CheckLoginInterceptor implements HandlerInterceptor {

    @Autowired
    private IUserInfoRedisService userInfoRedisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {

        // 排除跨域问题
       if(!(handler instanceof HandlerMethod)){
           return true;
       }
        // 通过获取请求头中的token,获取用户对象
        String token = request.getHeader("token");
        UserInfo userInfo = userInfoRedisService.getUserByToken(token);

        HandlerMethod hm = (HandlerMethod) handler;
        // 1.判断发送过来的请求映射方法上是否贴有注解(@RequiredLogin)
        // 2.如果有就进行登录效验
        if(hm.hasMethodAnnotation(RequiredLogin.class)){
            // 对贴有标签的方法,判断是否有用户数据,没有的话提示
            if(userInfo == null){
                response.setContentType("application/json;charset:UTF-8");
                response.getWriter().write(JSON.toJSONString(JsonResult.noLogin()));
                return false;
            }
        }
        // 3.没有贴注解就说明不需要登录就能操作
        return true;
    }
}
